package pres.moling.common.tool.reflect;

import java.lang.reflect.Field;
import java.util.Objects;

public interface ReflectUtil {

    /**
     *
     */


    /**
     * 对象初始化
     */
    static <T> T newInstance(Class<T> clazz) {
        try {
            return clazz.getConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 设置属性值
     */
    static <T> void setField(T src, String name, Object object) {

        try {
            Field field = src.getClass().getField(name);
            field.setAccessible(true);
            field.set(src, object);
        } catch (Exception e) {
            throw new RuntimeException("设置对象属性出错", e);
        }
    }

    static <T> Object getFieldValue(T src, String name) {
        try {
            return src.getClass().getField(name).get(src);
        } catch (Exception e) {
            throw new RuntimeException("获取属性值失败", e);
        }
    }

    /**
     * 获取字段属性对象
     */
    static <T> Field getField(T src, String name) {
        try {
            return src.getClass().getField(name);
        } catch (Exception e) {
            throw new RuntimeException("获取属性失败", e);
        }
    }

    /**
     * 属性复制
     *
     * @param src    源对象
     * @param tar    目标对象
     * @param isOver 目标对象值存在时是否覆写
     */
    static <T, R> void copyAttr(T src, R tar, boolean isOver) {
        try {
            Field tarField;
            for (Field field : src.getClass().getFields()) {
                tarField = tar.getClass().getField(field.getName());
                if (isOver || Objects.isNull(tarField.get(tar))) {
                    tarField.setAccessible(true);
                    tarField.set(tar, field.get(src));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("对象属性复制失败", e);
        }
    }


}
